import { defineStore } from 'pinia'
import { ref, reactive, computed } from 'vue'
import {
  getUserLevel,
  calculateExpReward,
  checkLevelUp,
  generateDailyTasks,
  generateWeeklyTasks,
  getPredefinedAchievements,
  checkAchievementProgress,
  calculateStudyStreak,
  getRandomEncouragement,
  type Task,
  type Achievement,
  type LevelConfig,
} from '@/utils/gameUtils'

export const useGameStore = defineStore('game', () => {
  // 用户游戏化数据
  const userGameData = reactive({
    exp: 1250,
    points: 2840,
    level: 15,
    levelName: '探索者',
    studyStreak: 12,
    totalStudyHours: 45,
    completedCourses: 8,
    comments: 45,
    perfectExams: 3,
    helpCount: 12,
    excellentAssignments: 5,
    lastCheckinDate: new Date(Date.now() - 24 * 60 * 60 * 1000), // 昨天
    checkinDates: [] as Date[],
  })

  // 任务系统
  const dailyTasks = ref<Task[]>([])
  const weeklyTasks = ref<Task[]>([])
  const completedTasks = ref<Set<number>>(new Set())

  // 成就系统
  const achievements = ref<Achievement[]>([])
  const unlockedAchievements = ref<Set<number>>(new Set())

  // 排行榜数据
  const leaderboardData = reactive({
    points: [] as any[],
    streak: [] as any[],
    level: [] as any[],
  })

  // 积分商城
  const shopItems = ref([
    {
      id: 1,
      name: '课程优惠券',
      description: '可抵扣任意课程50元',
      image: 'https://via.placeholder.com/80x80/ff6b6b/ffffff?text=券',
      price: 500,
      stock: 100,
    },
    {
      id: 2,
      name: 'VIP会员体验',
      description: '7天VIP会员体验',
      image: 'https://via.placeholder.com/80x80/4ecdc4/ffffff?text=VIP',
      price: 1000,
      stock: 50,
    },
    {
      id: 3,
      name: '学习资料包',
      description: '精选学习资料合集',
      image: 'https://via.placeholder.com/80x80/45b7d1/ffffff?text=资料',
      price: 800,
      stock: 200,
    },
    {
      id: 4,
      name: '定制头像框',
      description: '专属头像装饰框',
      image: 'https://via.placeholder.com/80x80/96ceb4/ffffff?text=头像',
      price: 300,
      stock: 500,
    },
    {
      id: 5,
      name: '学习时长加倍卡',
      description: '使用后学习时长计算翻倍',
      image: 'https://via.placeholder.com/80x80/ffa726/ffffff?text=加倍',
      price: 600,
      stock: 80,
    },
    {
      id: 6,
      name: '经验值加速器',
      description: '使用后获得经验值翻倍',
      image: 'https://via.placeholder.com/80x80/66bb6a/ffffff?text=加速',
      price: 400,
      stock: 150,
    },
  ])

  // 计算属性
  const currentLevelInfo = computed(() => {
    return getUserLevel(userGameData.exp)
  })

  const userStats = computed(() => ({
    completedCourses: userGameData.completedCourses,
    studyStreak: userGameData.studyStreak,
    comments: userGameData.comments,
    perfectExams: userGameData.perfectExams,
    studyHours: userGameData.totalStudyHours,
    helpCount: userGameData.helpCount,
    excellentAssignments: userGameData.excellentAssignments,
  }))

  // 初始化游戏数据
  const initializeGameData = () => {
    // 初始化任务
    dailyTasks.value = generateDailyTasks()
    weeklyTasks.value = generateWeeklyTasks()

    // 初始化成就
    achievements.value = getPredefinedAchievements()
    updateAchievements()

    // 初始化排行榜数据
    initializeLeaderboard()

    // 计算连续学习天数
    calculateCurrentStreak()
  }

  // 更新成就进度
  const updateAchievements = () => {
    achievements.value = checkAchievementProgress(achievements.value, userStats.value)

    // 检查新解锁的成就
    achievements.value.forEach((achievement) => {
      if (achievement.unlocked && !unlockedAchievements.value.has(achievement.id)) {
        unlockedAchievements.value.add(achievement.id)
        // 这里可以触发成就解锁通知
        console.log(`成就解锁: ${achievement.title}`)
      }
    })
  }

  // 计算当前连续学习天数
  const calculateCurrentStreak = () => {
    userGameData.studyStreak = calculateStudyStreak(userGameData.checkinDates)
  }

  // 添加经验值
  const addExperience = (action: string, difficulty: 'easy' | 'medium' | 'hard' = 'medium') => {
    const oldExp = userGameData.exp
    const expReward = calculateExpReward(action, difficulty)

    userGameData.exp += expReward

    // 检查是否升级
    const levelUp = checkLevelUp(oldExp, userGameData.exp)
    if (levelUp) {
      // 升级奖励
      userGameData.points += levelUp.rewards.points
      console.log(`恭喜升级到 ${levelUp.name}！获得 ${levelUp.rewards.points} 积分奖励`)
    }

    // 更新等级信息
    const levelInfo = getUserLevel(userGameData.exp)
    userGameData.level = levelInfo.level
    userGameData.levelName = levelInfo.name
  }

  // 添加积分
  const addPoints = (points: number) => {
    userGameData.points += points
  }

  // 消费积分
  const spendPoints = (points: number): boolean => {
    if (userGameData.points >= points) {
      userGameData.points -= points
      return true
    }
    return false
  }

  // 完成任务
  const completeTask = (taskId: number) => {
    const allTasks = [...dailyTasks.value, ...weeklyTasks.value]
    const task = allTasks.find((t) => t.id === taskId)

    if (task && !task.completed) {
      task.completed = true
      completedTasks.value.add(taskId)

      // 添加积分奖励
      addPoints(task.reward)

      // 添加经验值
      addExperience('task_completion')

      return true
    }
    return false
  }

  // 领取任务奖励
  const claimTaskReward = (taskId: number): boolean => {
    const allTasks = [...dailyTasks.value, ...weeklyTasks.value]
    const task = allTasks.find((t) => t.id === taskId)

    if (task && task.completed && !task.claimed) {
      task.claimed = true
      return true
    }
    return false
  }

  // 学习打卡
  const checkin = () => {
    const today = new Date()
    today.setHours(0, 0, 0, 0)

    const lastCheckin = new Date(userGameData.lastCheckinDate)
    lastCheckin.setHours(0, 0, 0, 0)

    // 检查是否已经打卡
    if (today.getTime() === lastCheckin.getTime()) {
      return { success: false, message: '今天已经打卡了' }
    }

    // 添加打卡记录
    userGameData.checkinDates.push(today)
    userGameData.lastCheckinDate = today

    // 计算连续天数
    calculateCurrentStreak()

    // 奖励
    addExperience('daily_checkin')
    addPoints(30)

    return {
      success: true,
      message: `打卡成功！连续学习 ${userGameData.studyStreak} 天`,
      streak: userGameData.studyStreak,
    }
  }

  // 购买商城物品
  const purchaseShopItem = (itemId: number): boolean => {
    const item = shopItems.value.find((i) => i.id === itemId)

    if (item && item.stock > 0 && spendPoints(item.price)) {
      item.stock--
      return true
    }
    return false
  }

  // 更新学习统计
  const updateLearningStats = (
    stats: Partial<{
      completedCourses: number
      totalStudyHours: number
      comments: number
      perfectExams: number
      helpCount: number
      excellentAssignments: number
    }>,
  ) => {
    Object.assign(userGameData, stats)
    updateAchievements()
  }

  // 初始化排行榜
  const initializeLeaderboard = () => {
    // 模拟排行榜数据
    leaderboardData.points = [
      {
        id: 1,
        nickname: '学霸小王',
        avatar: 'https://joeschmoe.io/api/v1/1',
        level: 20,
        points: 5680,
      },
      {
        id: 2,
        nickname: '学习达人',
        avatar: 'https://joeschmoe.io/api/v1/2',
        level: 15,
        points: 2840,
      },
      {
        id: 3,
        nickname: '知识探索者',
        avatar: 'https://joeschmoe.io/api/v1/3',
        level: 18,
        points: 4520,
      },
      {
        id: 4,
        nickname: '编程新手',
        avatar: 'https://joeschmoe.io/api/v1/4',
        level: 12,
        points: 2100,
      },
      {
        id: 5,
        nickname: '技术小白',
        avatar: 'https://joeschmoe.io/api/v1/5',
        level: 10,
        points: 1800,
      },
    ]

    leaderboardData.streak = [
      {
        id: 1,
        nickname: '坚持达人',
        avatar: 'https://joeschmoe.io/api/v1/6',
        level: 16,
        streak: 45,
      },
      {
        id: 2,
        nickname: '学习达人',
        avatar: 'https://joeschmoe.io/api/v1/2',
        level: 15,
        streak: 12,
      },
      {
        id: 3,
        nickname: '每日打卡',
        avatar: 'https://joeschmoe.io/api/v1/7',
        level: 14,
        streak: 8,
      },
      {
        id: 4,
        nickname: '勤奋学习',
        avatar: 'https://joeschmoe.io/api/v1/8',
        level: 13,
        streak: 6,
      },
      {
        id: 5,
        nickname: '新手入门',
        avatar: 'https://joeschmoe.io/api/v1/9',
        level: 11,
        streak: 3,
      },
    ]

    leaderboardData.level = [
      {
        id: 1,
        nickname: '至尊大神',
        avatar: 'https://joeschmoe.io/api/v1/10',
        level: 25,
        levelName: '至尊',
      },
      {
        id: 2,
        nickname: '传奇人物',
        avatar: 'https://joeschmoe.io/api/v1/11',
        level: 22,
        levelName: '传奇',
      },
      {
        id: 3,
        nickname: '专家级',
        avatar: 'https://joeschmoe.io/api/v1/12',
        level: 20,
        levelName: '专家',
      },
      {
        id: 4,
        nickname: '进阶者',
        avatar: 'https://joeschmoe.io/api/v1/13',
        level: 18,
        levelName: '进阶者',
      },
      {
        id: 5,
        nickname: '熟练工',
        avatar: 'https://joeschmoe.io/api/v1/14',
        level: 16,
        levelName: '熟练者',
      },
    ]
  }

  // 获取随机鼓励语
  const getEncouragement = () => {
    return getRandomEncouragement()
  }

  // 重置每日任务
  const resetDailyTasks = () => {
    dailyTasks.value = generateDailyTasks()
    completedTasks.value.clear()
  }

  // 重置每周任务
  const resetWeeklyTasks = () => {
    weeklyTasks.value = generateWeeklyTasks()
  }

  return {
    // 状态
    userGameData,
    dailyTasks,
    weeklyTasks,
    completedTasks,
    achievements,
    unlockedAchievements,
    leaderboardData,
    shopItems,

    // 计算属性
    currentLevelInfo,
    userStats,

    // 方法
    initializeGameData,
    addExperience,
    addPoints,
    spendPoints,
    completeTask,
    claimTaskReward,
    checkin,
    purchaseShopItem,
    updateLearningStats,
    updateAchievements,
    getEncouragement,
    resetDailyTasks,
    resetWeeklyTasks,
  }
})
